/**
 * 
 */
package com.tcl.wip.client;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.tcl.wip.client.repository.DatasourceManager;
import com.tcl.wip.client.sync.DbNode;
import com.tcl.wip.commons.constants.ContentType;
import com.tcl.wip.commons.utils.HttpClient;
import com.tcl.wip.commons.utils.JsonParser;

/**
 * @author zhaowen.zhuang
 * @Date Jan 26, 2015
 */
public class WipApp {

    public WipApp(String appId, String appKey, String server) {
        this.appId = appId;
        this.appKey = appKey;
        this.server = server;
        this.init();
    }

    private String server;

    private String appId;

    private String appKey;

    public DatasourceManager datasourceManager;

    private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(1);


    public void init() {
        datasourceManager = new DatasourceManager(this);
        Map<Long, DbNode> dbNodes = syncDbNode();
        datasourceManager.init(dbNodes);
        scheduledService.schedule(new Runnable() {

            @Override
            public void run() {
                Map<Long, DbNode> dbNodes = WipApp.this.syncDbNode();
                datasourceManager.update(dbNodes);
            }
        }, 5, TimeUnit.MINUTES);
    }

    public Map<Long, DbNode> syncDbNode() {
        String url = server + "/app/" + appId + "/nodes";
        String json = HttpClient.doGet(url);
        List<DbNode> dbNodes = JsonParser.parseParametricType(json, List.class, DbNode.class);

        Map<Long, DbNode> map = Maps.uniqueIndex(dbNodes, new Function<DbNode, Long>() {

            @Override
            public Long apply(DbNode input) {
                return input.getId();
            }
        });

        return map;
    }

    public DatasourceManager getDatasourceManager() {
        return datasourceManager;
    }

    public String getServer() {
        return server;
    }

    public String getAppId() {
        return appId;
    }



}
